package cn.bjit.service.impl;

import cn.bjit.config.OSSConfig;
import cn.bjit.service.FileService;
import cn.bjit.util.CommonUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
   private OSSConfig ossConfig;

    @Override
    public String uploadUserImg(MultipartFile file) {
        String bucketname = ossConfig.getBucketname();
        String accessKeyId = ossConfig.getAccessKeyId();
        String endpoint = ossConfig.getEndpoint();
        String accesskeySecret = ossConfig.getAccesskeySecret();

        //构建oss客户端
         OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accesskeySecret);
         //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取日期
        LocalDateTime ldt=LocalDateTime.now();
        DateTimeFormatter  dtf=DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String folder= dtf.format(ldt);
        //a.jpg
        String fileName = CommonUtil.generateUUID();
        String extendsion=originalFilename.substring(originalFilename.lastIndexOf("."));
        //在oss Bucke创建文件夹
        String newFileName="account/"+folder+"/"+fileName+extendsion;
        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketname, newFileName, file.getInputStream());
            if(putObjectResult!=null){
                String  imageUrl="https://"+bucketname+"."+endpoint+"/"+newFileName;
                return imageUrl;
            }
        } catch (IOException e) {
           log.error("文件上传失败{}",e.getMessage());

        }finally {
            ossClient.shutdown();
        }
        return null;
    }
}
